@<template>
  <div>
    <!-- 面包屑导航区域 -->
    <breadcrumb :breadInfo="breadInfo"></breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row>
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              @click="getUserList"
              slot="append"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button class="search-button" type="primary" @click="addUser"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- table展示区域 -->
      <el-table :data="userList" border style="width: 100%">
        
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="role_name" label="等级"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStatusChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUser(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="设置"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="settingUser(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 6, 20, 40]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalUserNum"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUserDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 添加内容区域 -->
      <el-form
        :model="addUserForm"
        :rules="addUserFormRules"
        ref="addUserFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserHandler"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog 
     title="修改用户信息"
      :visible.sync="editUserDialogVisible"
      width="50%"
      @close="editDialogClosed">
       <!-- 添加内容区域 -->
      <el-form
        :model="editUserForm"
        :rules="editUserFormRules"
        ref="editUserFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username" >
          <el-input disabled v-model="editUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserHandler"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 用户分配权限对话框 -->
    <el-dialog
    title="分配角色"
    :visible.sync="setUserRolesdialogVisible"
    width="50%"
    ref="setUserRolesRef"
    @close="editDialogClosed"
    >
    <div>
      <p>当前的用户:{{userInfo.username}}</p>
      <p>当前的角色:{{userInfo.role_name}}</p>
      <p>分配新角色:
        <el-select v-model="selectRoleId" placeholder="请选择" ref="roleSelectRef">
        <el-option
          v-for="item in rolesList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id">
        </el-option>
      </el-select>
      </p>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="setUserRolesdialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
    </span>
  </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from "../../common/breadcrumb/Breadcrumb.vue";

export default {
  components: {
    Breadcrumb,
  },
  data() {
     // 邮箱验证规则
      var checkEmail = (rule, value, cb) => {
        const regEmail = /^\w+((.\w+)|(-\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$/;
        if(regEmail.test(value)) {
          // 合法邮箱
          return cb()
        }
        cb(new Error("请输入合法的邮箱"))
      }

      // 手机号验证规则
      var checkPhoneNumber = (rule, value, cb) => {
        const regPhonNumber = /^[1][3,4,5,7,8,9][0-9]{9}$/;
        if (regPhonNumber.test(value)) {
          // 合法手机号
          return cb()
        }
        cb(new Error("请输入正确的手机号"))
      }
    return {
      queryInfo: {
        query: "",
        pagenum: 2,
        pagesize: 2,
      },
      breadInfo: ["用户管理", "用户列表"],
      totalUserNum: 1,
      userList: [],
      addUserDialogVisible: false,
      addUserForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      editUserForm: {},//编辑用户
      editUserDialogVisible: false,

      // 添加用户,用户信息验证规则
      addUserFormRules: {
        username: [
          {required: true, message: "请输入用户名", trigger: "blur"},
          { min: 3, max: 16, message: "3到16位之间", trigger: "blur"}
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"},
          { min: 6, max: 16, message: "6到16位之间", trigger: "blur"}
        ],
        email: [
          {required: true, message: "请输入邮箱", trigger: "blur"},
          {validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: "请输入手机号", trigger: "blur"},
          {validator: checkPhoneNumber, trigger: 'blur'}
        ]
      },
      // 修改用户 验证规则
      editUserFormRules: {
        email: [
          {required: true, message: "请输入邮箱", trigger: "blur"},
          {validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: "请输入手机号", trigger: "blur"},
          {validator: checkPhoneNumber, trigger: 'blur'}
        ]
      },
      // 控制 分配角色的对话框 的显示或隐藏
      setUserRolesdialogVisible: false,
      // 角色信息
      userInfo: {},
      // 所有角色列表
      rolesList: [],
      // 下拉选中的角色id
      selectRoleId: ''
    }
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) return this.$message.error("数据获取失败");
      this.userList = res.data.users;
      console.log(this.userList)

      this.totalUserNum = res.data.total;
    },
    // 监听pagesize发生改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },

    // 页码值发生改变
    handleCurrentChange(pageNum) {
      console.log(pageNum);
      this.queryInfo.pagenum = pageNum;
      this.getUserList();
    },
    // 用户状态发生改变, 触发的事件处理函数
    async userStatusChanged(userInfo) {
      console.log(userInfo)
      const {data: res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !==200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error("用户状态修改失败")
      }
      this.$message.success("用户状态修改成功")
    },
    // 添加用户
    addUser() {
      this.addUserDialogVisible = true
    },
    // 添加用户对话框关闭触发的函数
    addDialogClosed() {
      this.$refs.addUserFormRef.resetFields()
    },
    // 添加用户的方法
    addUserHandler() {
      // 表单预验证
      this.$refs.addUserFormRef.validate( async valid => {

        if (!valid) return 

        // 验证通过,开始发起网络请求
        const {data: res} = await this.$http.post("users", this.addUserForm)
        if (res.meta.status !== 201) return this.$message.error("用户添加失败")
        
        this.$message.success("添加用户成功")
        this.addUserDialogVisible = false

      })
    },
    // 修改用户
    async editUser(userInfo) {
      // 发送网络请求
      const {data: res} = await this.$http.get(`users/${userInfo.id}`)
      if (res.meta.status !== 200) return this.$message.error("获取用户信息失败!")
      this.editUserForm = res.data
      this.editUserDialogVisible = true

    },
    // 修改用户 确认按钮
    editUserHandler() {
      // 表单预验证
      this.$refs.editUserFormRef.validate(async valid => {
        if (!valid) return 

        // 验证成功, 开始发送网络请求
        const {data: res} = await this.$http.put(`users/${this.editUserForm.id}`, {email: this.editUserForm.email, mobile: this.editUserForm.mobile})
        if (res.meta.status !== 200) return this.$message.error("用户信息修改失败")

        // 修改成功
        this.$message.success("修改成功")

        // 刷新列表
        this.getUserList()
        // 关闭对话框
        this.editUserDialogVisible = false

      })

    },
    // 修改用户 对话框 关闭事件
    editDialogClosed() {
      // 重置对话框
      this.$refs.editUserFormRef?.resetFields()
      // 重置 选择角色 对话框
      this.selectRoleId = ""
      
      this.userInfo = {}

    },

    // 删除按钮
    deleteUser(userInfo) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        // 发送网络请求, 删除用户
        const {data: res} = await this.$http.delete(`users/${userInfo.id}`)
        if (res.meta.status !== 200) return  this.$message.info("取消删除")
        this.getUserList()
        this.$message.success("删除成功")
        
        
      }).catch(() => {
        this.$message.info("取消删除")
      }) 
    },
    // 点击设置用户图标
    async settingUser(userInfo){
      this.userInfo = userInfo
      // 获取所有角色列表
      const {data: res} = await this.$http.get("roles")
      if (res.meta.status !== 200) return this.$message.error("获取角色列表失败")  
      this.rolesList = res.data

      // 展示分配角色对话框
      this.setUserRolesdialogVisible = true
    }, 
    async saveRoleInfo() {
      // 验证是否选择角色
      if(!this.selectRoleId) return this.$message.error("请选择要分配的角色")

      // 发起分配角色请求
      const {data: res}  = await this.$http.put(`users/${this.userInfo.id}/role`,{rid: this.selectRoleId})
      
      if (res.meta.status !== 200) return this.$message.error("角色分配失败")
      this.$message.success("角色分配成功")
      
      // 更新数据
      this.getUserList()
      // 关闭对话框
      this.setUserRolesdialogVisible = false

    }
  },
};
</script>
<style lang="less" scoped>


</style> 

